<?php
/*
Plugin Name: مدیریت بازار تایر هرمزگان
Plugin URI: http://tire.asnafhormozgan.com
Description: افزونه سیستم تنظیم بازار لاستیک خودرو اصناف هرمزگان
Version: 2.0
Author: saeb Molaee & <a href="https://abdolvahidvahedi.ir/">Abdolvahid Vahedi</a>
Author URI: http://saeb.id.ir
License: A "Slug" license name e.g. GPL2
*/

/*//wordpress interactive cli https://jondavidjohn.com/interactive-wordpress-php-shell/

 *<?php
    // assumes this file is placed in ../wp
    define('CLI_WP_ROOT', dirname(__FILE__));
    $_SERVER['HTTP_HOST'] = 'http://localhost:8008';

    ob_start();
    require_once(CLI_WP_ROOT.'/wp-load.php');
    require_once(ABSPATH.'wp-admin/includes/admin.php');
    ob_end_clean();
    $tire_gravity_form_id = 2;
 */
defined( 'ABSPATH' ) or die( 'No script kiddies please!' );
define( 'tiremanager_plugin_dir_path', plugin_dir_path( __FILE__ ) );
define( 'tiremanager_plugin_dir_url', plugin_dir_url( __FILE__ ) );
date_default_timezone_set( 'Asia/Tehran' );
require( tiremanager_plugin_dir_path . 'sellers_gf_admin.php' );
require( tiremanager_plugin_dir_path . 'gf_validator.php' );
require( tiremanager_plugin_dir_path . 'gf_confirms.php' );
require( tiremanager_plugin_dir_path . 'invoice_add.php' );
require( tiremanager_plugin_dir_path . 'invoicelist.php' );
require( tiremanager_plugin_dir_path . 'lastdbchange.php' );
require( tiremanager_plugin_dir_path . 'tm_shortcode.php' );
if ( ! function_exists( 'get_home_path' ) ) {
	include_once ABSPATH . '/wp-admin/includes/file.php';
}
if ( ! function_exists( 'jdate' ) ) {
	require( tiremanager_plugin_dir_path . 'lib/jdf.php' );

}
if ( ! function_exists( 'err_log' ) ) {
	function err_log( $obj ) {
		if ( ! WP_DEBUG ) {
			return;
		}
		$log = print_r( $obj, true );
		echo "
    <script>
    console.debug('$log');
</script>
    ";
		error_log( $log );
	}
}
function is_tatil( $jalali_date ) {// 1397-01-01
	require( tiremanager_plugin_dir_path . 'lib/holidays.php' );
	$jalali_epoch = jalaliepoch( $jalali_date );
	$day_of_week  = ( intval( ( $jalali_epoch['date']->format( 'N' ) ) + 1 ) % 7 );
	$hdate        = $jalali_epoch['hijri'];
	$hmonth       = $hdate['month'];
	$hday         = $hdate['day'];
	list ( $jyear, $jmonth, $jday ) = explode( '-', $jalali_date );
	$jalali_holidays = $holidays['holidays']['jalali'];
	$hijri_holidays  = $holidays['holidays']['hijri'];
	$tatil           = $day_of_week;
	if ( in_array( array( intval( $jmonth ), intval( $jday ) ), $jalali_holidays ) ) {
		$tatil = 8;
	}
	if ( in_array( array( intval( $hmonth ), intval( $hday ) ), $hijri_holidays ) ) {
		$tatil = 9;
	}
	//err_log( "روز هفته" );
	//err_log( print_r( $day_of_week, true ) );

	return $tatil;//bala 5 tatil
}

function installation_db() {
	global $wpdb;
//    $wpdb->print_error();
	include( tiremanager_plugin_dir_path . 'formsconfig.php' );
	$table_name                     = $wpdb->prefix . $tire_table_quantities_without_prefix_name;
	$table_viw_name                     = $wpdb->prefix .'viw_'. $tire_table_quantities_without_prefix_name;
	$table_name_invoices            = $wpdb->prefix . $tire_table_werehouse_invoices_prefix_name;
	$table_name_tire_manager_option = $wpdb->prefix . $tire_table_option;
	$charset_collate                = $wpdb->get_charset_collate();
//    add_role("tire_seller","عامل فروش لاستیک",array('read'=>true));
//    add_role("tire_seller_admin","مدیریت فروش لاستیک",array('read'=>true));

	$sql          = "CREATE TABLE IF NOT EXISTS $table_name (
  id int UNSIGNED not null unique AUTO_INCREMENT,
  tire_seller varchar(50) NOT NULL,
  tire_type_is_sabok bool default true,
  tire_is_active bool default true,
  tire_brand varchar(50) NOT NULL,
  tire_size varchar(50) NOT NULL,
  tire_quantity smallint unsigned default 0,
  date_updated datetime default CURRENT_TIMESTAMP,
  added_by varchar(50),
  invoice_number varchar(50),
  PRIMARY KEY  (id)
) $charset_collate;";


	$sql_invoices = "CREATE TABLE IF NOT EXISTS $table_name_invoices (
  id int UNSIGNED not null unique AUTO_INCREMENT,
  tire_seller varchar(50) NOT NULL,
  date_updated datetime default CURRENT_TIMESTAMP,
  added_by varchar(50),
  invoice_number varchar(20),
  invoice_date varchar(20),
  invoice_image varchar(200),
  PRIMARY KEY  (id)
) $charset_collate;";

	$tire_manager_options = "CREATE TABLE IF NOT EXISTS $table_name_tire_manager_option
(
    id int UNSIGNED not null unique AUTO_INCREMENT,
	create_date datetime default current_timestamp not null,
	create_by tinytext null,
	last_modified_date datetime null,
	option_key varchar(50) unique not null,
	option_description tinytext ,
	option_value text not null,
	constraint tire_manager_option_pk
		primary key (id)
) $charset_collate;
";
$sql_viw_query = "CREATE OR REPLACE VIEW  $table_viw_name AS
            SELECT  * FROM $table_name WHERE id IN (
                                            SELECT MAX(id) AS id
                                            FROM $table_name
                                            GROUP BY tire_seller, tire_brand, tire_size
                                            )
	";
	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	dbDelta( $sql );
	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	dbDelta( $tire_manager_options );
	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	dbDelta( $sql_invoices );
    global $wpdb;
    $wpdb->query($sql_viw_query);
	add_sellers_brand_size_to_db();
}


function tire_get_legal_seller_brand_size() {
	require( tiremanager_plugin_dir_path . 'sellers_brands.php' );
	require( tiremanager_plugin_dir_path . 'formsconfig.php' );
	$tire_table_array = array();
	foreach ( $sellers_array as $sellers_name => $seller ) {
		if ( ! username_exists( $sellers_name ) ) {
			wp_create_user( $sellers_name, wp_generate_password( 6 ), "$sellers_name@hormozgantire.ir" );
			$u = get_user_by( 'login', $sellers_name );
//            $u->set_role('tire_seller');
			update_user_meta( $u->ID, 'first_name', $seller['farsi_name'] );
		}
		$tire_seller_sells_sabok  = in_array( 'sabok', $seller['tire_type'] );
		$tire_seller_sells_sangin = in_array( 'sangin', $seller['tire_type'] );
		foreach ( $seller['brands'] as $brand_name ) {
			$brand                   = $brands_array[ $brand_name ];
			$tire_sabok_is_in_brand  = array_key_exists( 'sabok', $brand['type'] );
			$tire_sangin_is_in_brand = array_key_exists( 'sangin', $brand['type'] );
			if ( $tire_seller_sells_sangin ) {
				if ( $tire_sangin_is_in_brand ) {

					foreach ( $brands_array[ $brand_name ]['type']['sangin'] as $size ) {
						$seller_table_array = array( $seller, $brand, $size, false );
						array_push( $tire_table_array, $seller_table_array );
					}
				}
			}
			if ( $tire_seller_sells_sabok ) {
				if ( $tire_sabok_is_in_brand ) {
					foreach ( $brands_array[ $brand_name ]['type']['sabok'] as $size ) {
						$seller_table_array = array( $sellers_name, $brand_name, $size, true );
						array_push( $tire_table_array, $seller_table_array );
					}
				}
			}

		}
	}

	return $tire_table_array;

}

function add_sellers_brand_size_to_db() {
	global $wpdb;
	require( tiremanager_plugin_dir_path . 'sellers_brands.php' );
	include( tiremanager_plugin_dir_path . 'formsconfig.php' );
	$table_name       = $wpdb->prefix . $tire_table_quantities_without_prefix_name;
	$tire_table_array = tire_get_legal_seller_brand_size();
	foreach ( $tire_table_array as $row ) {
		$seller   = $row[0];
		$brand    = $row[1];
		$size     = $row[2];
		$is_sabok = $row[3];
//        error_log(print_r($row,true));
		$id = $wpdb->get_var( "
            select id
            from `$table_name`
            where `tire_seller`='$seller'
            and `tire_brand`='$brand'
            and `tire_size`='$size' ;
        " );
//        error_log("seller $seller  is $id ====");
		if ( $id == null ) {
//            error_log("we are in if $seller");

			$insert_array = array(
				'tire_seller'        => $seller,
				'tire_brand'         => $brand,
				'tire_size'          => $size,
				'tire_type_is_sabok' => $is_sabok,
				'added_by'           => 'plugin'
			);
			$wpdb->insert( $table_name, $insert_array );
		}
	}
	foreach ( $sellers_array as $seller => $value ) {
		$invoice_table = $wpdb->prefix . $tire_table_werehouse_invoices_prefix_name;
		$invoice_row   = $wpdb->get_var( "
        select max(id) from $invoice_table
            where `tire_seller`='$seller';
        " );
		if ( $invoice_row == null ) {
			$invoice_array = array(
				'tire_seller'    => $seller,
				'invoice_number' => 'اولیه',
				'added_by'       => 'plugin'

			);
			$wpdb->insert( $invoice_table, $invoice_array );
		}
	}
}

//gravityforms methods

function tire_save_invoice_path_url( $file ) {

	$base_dir         = wp_get_upload_dir()['basedir'];
	$base_url         = wp_get_upload_dir()['baseurl'];
	$tire_invoice_dir = "/invoice/";
	if ( ! file_exists( $tire_invoice_dir ) ) {
		wp_mkdir_p( $base_dir . $tire_invoice_dir );
	}

	return array(
		'file' => $base_dir . $tire_invoice_dir . "$file",
		'url'  => $base_url . $tire_invoice_dir . "$file"
	);
}

function hiadmin() {
	echo "
    سلام مدیر. کاری اینجا نیست درواقع با یوزر عاملها بیا و سایت رو تست کن
    ";
}

//page methids #todo rename
function tire_limit_admin_menu() {
	include( tiremanager_plugin_dir_path . 'formsconfig.php' );
	include tiremanager_plugin_dir_path . 'sellers_brands.php';
	$u           = wp_get_current_user();
	$username    = $u->user_login;
	$seller_list = array();
	foreach ( $sellers_array as $item => $value ) {
		array_push( $seller_list, $item );
	}
	if ( ! current_user_can( 'level_9' ) ) {
		remove_menu_page( 'index.php' );
		remove_menu_page( 'edit.php' );
		remove_menu_page( 'edit-comments.php' );
		remove_menu_page( 'tools.php' );
		remove_menu_page( 'profile.php' );
		remove_menu_page( 'gf_entries' );
	}
	if ( current_user_can( 'level_1' ) or in_array( $username, $seller_list ) ) {
		if ( current_user_can( 'level_1' ) ) {
			if ( ! $tire_ware_house_limit ) {
				add_menu_page(
					'سلام مدیر',
					'سلام مدیر',
					'level_1',
					'hiadmin',
					'hiadmin',
					plugin_dir_url( __FILE__ ) . 'images/icontire.svg',
					20
				);
				add_submenu_page(
					'hiadmin',
					'گزارش تغییرات',
					'گزارش تغییرات',
					'level_1',
					'lastdbchange',
					'last_db_change' );
			}
			if ( $tire_ware_house_limit ) {

				add_menu_page(
					'لیست موجودی',
					'موجودی لاستیک',
					'level_0',
					'tireadmin',
					'tire_limit_admin_page',
					plugin_dir_url( __FILE__ ) . 'images/icontire.svg',
					20
				);
				add_submenu_page(
					'tireadmin',
					'جست و جو ثبت‌نامی‌ها',
					'جست و جو',
					'level_0',
					'gf_inbox_search',
					'search_tires' );
				add_submenu_page(
					'tireadmin',
					'ثبت‌نامی‌های تحویل شده',
					'تحویل شده',
					'level_0',
					'gf_inbox_delivered',
					'delivered_gf_inbox' );


				add_submenu_page(
					'tireadmin',
					'ویرایش موجودی',
					'ویرایش موجودی',
					'level_0',
					'tireedit',
					'edit_tire_page' );
				add_submenu_page(
					'tireadmin',
					'ثبت‌نامی‌های مشاهده شده',
					'مشاهده شده',
					'level_0',
					'gf_inbox_read',
					'read_gf_inbox' );
				add_submenu_page(
					'tireadmin',
					'ثبت‌نامی‌های جدید',
					'ثبت‌نامی جدید',
					'level_0',
					'gf_inbox_new',
					'new_gf_inbox' );


				add_submenu_page(
					'tireadmin',
					'گزارش تغییرات',
					'گزارش تغییرات',
					'level_1',
					'lastdbchange',
					'last_db_change' );
				if ( $invoice_management ) {

					add_submenu_page(
						'tireadmin',
						'افزودن فاکتور ورودی محموله به انبار',
						'افزودن فاکتور',
						'level_0',
						'add_invoice',
						'add_invoice' );
					add_submenu_page(
						'tireadmin',
						'مشاهده فاکتورهای ثبت شده',
						'فاکتورها',
						'level_0',
						'invoicelist',
						'invoicelist' );

				}

			}


		} else {
			add_menu_page(
				'لیست متقاضیان در انتظار تحویل(فقط لیست لاستیک های تحویل نشده)',
				'متقاضیان در انتظار تحویل',
				'level_0',
				'gf_inbox_new',
				'new_gf_inbox',
				plugin_dir_url( __FILE__ ) . 'images/icontire.svg',
				20
			);
			add_submenu_page(
				'gf_inbox_new',
				'جستجوی متقاضیان',
				'جستجوی متقاضیان',
				'level_0',
				'gf_inbox_search',
				'search_tires' );
			add_submenu_page(
				'gf_inbox_new',
				'لیست کل متقاضیان (شامل تحویل شده و نشده)',
				'لیست کل متقاضیان',
				'level_0',
				'gf_inbox_all',
				'all_registered_gf_inbox'
//					'delivered_gf_inbox'
			);
			add_submenu_page(
				'gf_inbox_new',
				'لیست دریافت‌کنندگان لاستیک (فقط لیست لاستیک های تحویل شده)',
				'دریافت‌کنندگان لاستیک',
				'level_0',
				'gf_inbox_delivered',
				'delivered_gf_inbox' );

//			add_submenu_page(
//				'gf_inbox_new',
//				'ثبت‌نامی‌های مشاهده شده',
//				'مشاهده شده',
//				'level_0',
//				'gf_inbox_read',
//				'read_gf_inbox' );

//			if ( $tire_ware_house_limit and $seller_allow_edit_warehouse_limit ) {
//            add_menu_page(
//                'لیست موجودی',
//                'موجودی تایرها',
//                'level_0',
//                'tireadmin',
//                'tire_limit_admin_page',
//                plugin_dir_url(__FILE__) . 'images/icontire.svg',
//                20
//            );
			add_submenu_page(
				'gf_inbox_new',
				'لیست موجودی',
				'موجودی لاستیک',
				'level_0',
				'tireadmin',
				'tire_limit_admin_page' );
			add_submenu_page(
				'tireadmin',
				'ویرایش موجودی',
				'ویرایش موجودی',
				'level_0',
				'tireedit',
				'edit_tire_page' );

//			}
			/*
			add_menu_page(
				'لیست موجودی',
				'موجودی تایرها',
				'level_0',
				'tireadmin',
				'tire_limit_admin_page',
				plugin_dir_url(__FILE__) . 'images/icontire.svg',
				20
			);
			*/

//        add_submenu_page(
//            'tireadmin',
//            'ثبت‌نامی‌های جدید',
//            'ثبت‌نامی‌های جدید',
//            'level_0',
//            'gf_inbox_new',
//            'new_gf_inbox');
			if ( $invoice_management and $seller_allow_edit_invoice ) {

				add_submenu_page(
					'tireadmin',
					'افزودن فاکتور ورودی محموله به انبار',
					'افزودن فاکتور',
					'level_0',
					'add_invoice',
					'add_invoice' );
				add_submenu_page(
					'tireadmin',
					'مشاهده فاکتورهای ثبت شده',
					'فاکتورها',
					'level_0',
					'invoicelist',
					'invoicelist' );

			}
//            add_submenu_page(
//                'tireadmin',
//                'ثبت‌نامی‌های جدید',
//                'ثبت‌نامی‌های جدید',
//                'level_0',
//                'gf_inbox_new',
//                'new_gf_inbox');
//            add_submenu_page(
//                'tireadmin',
//                'ثبت‌نامی‌های مشاهده شده',
//                'مشاهده شده',
//                'level_0',
//                'gf_inbox_read',
//                'read_gf_inbox');


		}
	}
}


function tire_get_url_variable( $string ) {
	if ( isset( $_GET[ $string ] ) ) {
		return $_GET[ $string ];
	} else {
		return false;
	}
}

function tire_get_post_url_variable( $string ) {
	if ( isset( $_POST[ $string ] ) ) {
		return $_POST[ $string ];
	} else {
		return '0';
	}
}

function edit_tire_page() {

	require( tiremanager_plugin_dir_path . 'formsconfig.php' );
	require( tiremanager_plugin_dir_path . 'sellers_brands.php' );
    /** @var array $brands_array */
	$tire_sizes_info = getAllTireSize($brands_array);
	if ( ! function_exists( 'jdate' ) ) {
		require( tiremanager_plugin_dir_path . 'lib/jdf.php' );

	}
	if ( ! current_user_can( 'level_0' ) ) {
		wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
	}
	include tiremanager_plugin_dir_path . 'sellers_brands.php';
	$u           = wp_get_current_user();
	$username    = $u->user_login;
	$seller_list = array();
	foreach ( $sellers_array as $item => $value ) {
		array_push( $seller_list, $item );
	}
	if ( isset( $_GET['redirecter'] ) ) {
		$is_redirect = true;
	} else {
		$is_redirect = false;
	}
	if ( ! $is_redirect and ! current_user_can( 'level_1' ) ) {
		include( tiremanager_plugin_dir_path . 'sellers_brands.php' );


		$seller_tire_types    = $sellers_array[ $username ]['tire_type'];
		$tire_sizes           = array();
		$tire_brands_eng_name = array();
		foreach ( $sellers_array[ $username ]['brands'] as $item ) {
			array_push( $tire_brands_eng_name, $item );
		}
		foreach ( $seller_tire_types as $tire_type ) {
			foreach ( $tire_brands_eng_name as $brand ) {
				$tire_sizes = array_merge( $tire_sizes, $brands_array[ $brand ]['type'][ $tire_type ] );
			}
		}
		$tire_sizes = array_unique( $tire_sizes );
		?>
        <script>
            var _validFileExtensions = [".jpg", ".jpeg", ".pdf", ".gif", ".png"];

            function Validate(oForm) {
                var arrInputs = oForm.getElementsByTagName("input");
                for (var i = 0; i < arrInputs.length; i++) {
                    var oInput = arrInputs[i];
                    if (oInput.type == "file") {
                        var sFileName = oInput.value;
                        var blnValid = false;
                        for (var j = 0; j < _validFileExtensions.length; j++) {
                            var sCurExtension = _validFileExtensions[j];
                            if (sFileName.substr(sFileName.length - sCurExtension.length,
                                sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                                blnValid = true;
                                break;
                            }
                        }

                        if (!blnValid) {
                            alert(" پسوندهای مجاز: " + _validFileExtensions.join(", "));
                            return false;
                        }

                    }
                }

                return true;
            }
        </script>
        <form enctype="multipart/form-data" id="tire_edit_form" method="post" action=""
              onsubmit="return Validate(this);">
            <table id="tire_edit_table">
                <thead>
                <tr>
                    <th>
                        عامل
                    </th>
                    <th>
                        برند
                    </th>
                    <th>
                        سایز
                    </th>
                    <th>
                        مقدار موجودی
                    </th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td>
                        <select name="tire_seller_selected">
                            <option value="<?php echo $username; ?>" selected>
								<?php
								echo $sellers_array[ $username ]['farsi_name'];
								?>
                            </option>
                        </select>
                    </td>
                    <td>
                        <select name="tire_brand_selected">
							<?php
							foreach ( $tire_brands_eng_name as $b ) {
								echo "<option value=\"$b\" ";
								$tire_brand_farsi_name = $brands_array[ $b ]['farsi_name'];
								echo ">" . $tire_brand_farsi_name . "</option>";
							}

							?>

                        </select>


                    </td>
                    <td>
                        <select name="tire_size_selected">
							<?php

							foreach ( $tire_sizes as $t ) {
								echo "<option value=\"$t\"";

								echo ">$t</option>";
							}
							?>
                        </select>
                    </td>
                    <td>
                        <input name="tire_quantity_selected" type="number" max="10000" value="<?php echo $quantity; ?>">
                    </td>
                </tr>
                </tbody>
				<?php
				if ( $invoice_management ) {
					?>
                    <thead>

                    <tr>
                        <th>
                            شماره فاکتور ورودی به انبار
                        </th>
                        <th>
                            به‌روز‌رسانی
                        </th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr>
                        <td>
							<?php
							global $wpdb;
							$table_name_warehouse = $wpdb->prefix . $tire_table_werehouse_invoices_prefix_name;
							$invoice_numbers      = $wpdb->get_col( "
                        select invoice_number from $table_name_warehouse
                        where `tire_seller`='$username'" );
							echo "<select name=invoice_number>";
							foreach ( $invoice_numbers as $invoice ) {
								echo "<option value='$invoice'>$invoice</option>";
							}
							echo "</select>";

							?>

                    </tr>
                    </tbody>
				<?php } ?>
                <tbody>
                </td>
                <td>
                    <input type="submit" value="ارسال">
                </td>
                </tbody>
            </table>
        </form>


		<?php
	}
	$seller   = tire_get_url_variable( 'seller' );
	$brand    = tire_get_url_variable( 'brand' );
	$size     = tire_get_url_variable( 'size' );
	$quantity = tire_get_url_variable( 'quantity' );
	if ( isset(
		     $_POST['tire_seller_selected'] ) and isset(
			                                          $_POST['tire_brand_selected'] ) and isset(
				                                                                              $_POST['tire_size_selected'] ) and isset(
				                                                                              $_POST['tire_quantity_selected'] )
	) {
		include tiremanager_plugin_dir_path . 'formsconfig.php';
		global $wpdb;
		$table_name        = $wpdb->prefix . $tire_table_quantities_without_prefix_name;
		$selected_seller   = tire_get_post_url_variable( 'tire_seller_selected' );
		$selected_brand    = tire_get_post_url_variable( 'tire_brand_selected' );
		$selected_size     = tire_get_post_url_variable( 'tire_size_selected' );
		$selected_quantity = tire_get_post_url_variable( 'tire_quantity_selected' );
		$invoice_number    = "اولیه";
		if ( $username == $selected_seller ) {
			if ( $invoice_management ) {
				if (
				! isset( $_POST['invoice_number'] )

				) {
					die( "شما اطلاعات فاکتور ورود به انبار را وارد نکردید." );
				}
				$invoice_number = tire_get_post_url_variable( 'invoice_number' );
				$invoice_row    = $wpdb->get_var( "
        select `date_updated`  from `$table_name`
        where `tire_seller` = '$selected_seller' and 
              `tire_brand` = '$selected_brand' and 
               `invoice_number` = '$invoice_number' and
              `tire_size` = '$selected_size'
                ORDER BY id DESC;
                            " );
				if ( $invoice_row != null ) {
					$date  = strtotime( $invoice_row );
					$jdate = jdate( 'Y-m-d H:i:s', $date );
					die( "به لاستیک 
                $selected_brand
                قبلا با شماره فاکتور
                
                $invoice_number
                و تاریخ
                $jdate
                ثبت شده. 
                شما مجاز نیستید با یک فاکتور ورودی انبار بیش‌از یک بار موجودی را تنظیم کنید.
                در صورت اشکال در موجودی انبار
                با مدیر سایت تماس بگیرید
                " );
				}
			}
			$row = $wpdb->get_var( "
        select id from `$table_name`
        where `tire_seller` = '$selected_seller' and 
              `tire_brand` = '$selected_brand' and 
              `tire_size` = '$selected_size';
        " );
			if ( $row == null ) {
				die( "نمیشه مقدار
             $selected_quantity
              رو به برند
               $selected_brand
               با سایز 
               $selected_size
               و عامل
               $selected_seller
               وصل کرد. احتمالا حق فروش همچین چیزی رو نداره." );
			} else {
				$tire_sabok_size_array = array();
				foreach ( $tire_gf_fields_id_tire_sizes['sabok'] as $tire_sabok_size_gf_field_id => $value ) {
					$tire_field               = GFAPI::get_field( $tire_gravity_form_id,
						$tire_sabok_size_gf_field_id );
					$tire_field               = $tire_field->choices;
					$tire_sabok_size_tmparray = array();
					foreach ( $tire_field as $tire ) {
						array_push( $tire_sabok_size_tmparray, $tire['text'] );
					}
					$tire_sabok_size_array = array_merge( $tire_sabok_size_array, $tire_sabok_size_tmparray );

				}
				$is_sabok     = in_array( $selected_size, $tire_sabok_size_array );
				$insert_array = array(
					'tire_seller'        => $selected_seller,
					'tire_brand'         => $selected_brand,
					'tire_size'          => $selected_size,
					'tire_type_is_sabok' => $is_sabok,
					'added_by'           => $username,
					'tire_quantity'      => $selected_quantity,
					'invoice_number'     => $invoice_number,
				);
				$saved        = $wpdb->insert( $table_name, $insert_array );
				if ( $saved ) {
					die( "ذخیره شد" );
				}

			}
		} elseif ( current_user_can( 'level_1' ) ) {
			$row = $wpdb->get_var( "
        select id from `$table_name`
        where `tire_seller` = '$selected_seller' and 
              `tire_brand` = '$selected_brand' and 
              `tire_size` = '$selected_size';
        " );
			if ( $row == null ) {
				die( "نمیشه مقدار
             $selected_quantity
              رو به برند
               $selected_brand
               با سایز 
               $selected_size
               و عامل
               $selected_seller
               وصل کرد. احتمالا حق فروش همچین چیزی رو نداره." );
			} else {
				$tire_sabok_size_array = array();
				foreach ( $tire_gf_fields_id_tire_sizes['sabok'] as $tire_sabok_size_gf_field_id => $value ) {
					$tire_field                = GFAPI::get_field( $tire_gravity_form_id,
						$tire_sabok_size_gf_field_id );
					$tire_field                = $tire_field->choices;
					$tire_sabok_size_tmp_array = array();
					foreach ( $tire_field as $tire ) {
						array_push( $tire_sabok_size_tmp_array, $tire['text'] );
					}
					$tire_sabok_size_array = array_merge( $tire_sabok_size_array, $tire_sabok_size_tmp_array );
				}
				$is_sabok     = in_array( $selected_size, $tire_sizes_info['sabok'] );
				$insert_array = array(
					'tire_seller'        => $selected_seller,
					'tire_brand'         => $selected_brand,
					'tire_size'          => $selected_size,
					'tire_type_is_sabok' => $is_sabok,
					'added_by'           => $username,
					'tire_quantity'      => $selected_quantity,
				);
				$saved        = $wpdb->insert( $table_name, $insert_array );
				if ( $saved ) {
					die( "<h1>


ذخیره شد

</h1>
" );
				}

			}
		}
		$row = $wpdb->get_var( "
        select id from `$table_name`
        where `tire_seller` = '$selected_seller' and 
              `tire_brand` = '$selected_brand' and 
              `tire_size` = '$selected_size';
        " );
		if ( $row == null ) {
			die( "نمیشه مقدار
             $selected_quantity
              رو به برند
               $selected_brand
               با سایز 
               $selected_size
               و عامل
               $selected_seller
               وصل کرد. احتمالا حق فروش همچین چیزی رو نداره." );
		} else {
			$tire_field            = GFAPI::get_field( $tire_gravity_form_id,
				$tire_sabok_size_gf_field_id );
			$tire_field            = $tire_field->choices;
			$tire_sabok_size_array = array();
			foreach ( $tire_field as $tire ) {
				array_push( $tire_sabok_size_array, $tire['text'] );
			}
			$is_sabok     = in_array( $selected_size, $tire_sabok_size_array );
			$insert_array = array(
				'tire_seller'        => $selected_seller,
				'tire_brand'         => $selected_brand,
				'tire_size'          => $selected_size,
				'tire_type_is_sabok' => $is_sabok,
				'added_by'           => $username,
				'tire_quantity'      => $selected_quantity,
			);
			$wpdb->insert( $table_name, $insert_array );
//            wp_safe_redirect( get_admin_url()."admin.php?page=tireadmin" );
//            exit;
		}

	}
	if ( current_user_can( 'level_1' ) ) {
		$tire_array = array();
		foreach ( $tire_gf_fields_id_tire_sizes['sabok'] as $tire_sangin_size_gf_field_id => $value ) {
			$tire_field     = GFAPI::get_field( $tire_gravity_form_id,
				$tire_sangin_size_gf_field_id );
			$tire_field     = $tire_field->choices;
			$tire_tmp_array = array();
			foreach ( $tire_field as $tire ) {
				array_push( $tire_tmp_array, $tire['text'] );
			}
			$tire_array = array_merge( $tire_array, $tire_tmp_array );
		}
		foreach ( $tire_gf_fields_id_tire_sizes['sabok'] as $tire_sabok_size_gf_field_id => $value ) {

			$tire_field = GFAPI::get_field( $tire_gravity_form_id,
				$tire_sabok_size_gf_field_id );
			$tire_field = $tire_field->choices;
			foreach ( $tire_field as $tire ) {
				array_push( $tire_array, $tire['text'] );
			}
			$tire_array = array_merge( $tire_array, $tire_tmp_array );

		}
		$tire_brands_eng_name = array();
		foreach ( $brands_array as $item => $value ) {
			array_push( $tire_brands_eng_name, $item );
		}
		$tire_array =  getAllTireSize($brands_array)['sizes'];

		?>
        <form id="tire_edit_form" method="post" action="">
            <table id="tire_edit_table">
                <thead>
                <tr>
                    <th>
                        عامل
                    </th>
                    <th>
                        برند
                    </th>
                    <th>
                        سایز
                    </th>
                    <th>
                        مقدار موجودی
                    </th>
                    <th>
                        به‌روز‌رسانی
                    </th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td>
                        <select name="tire_seller_selected">

							<?php
							foreach ( $seller_list as $s ) {
								echo "
                                <option value=\"$s\" ";
								if ( $s == $seller ) {
									echo 'selected';
								}

								echo '>' . $sellers_array[ $s ]['farsi_name'] . " </option>";

							}
							?>
                        </select>
                    </td>
                    <td>
                        <select name="tire_brand_selected">
							<?php
							foreach ( $tire_brands_eng_name as $b ) {
								echo "<option value=\"$b\" ";
								if ( $b == $brand ) {
									echo " selected";
								}
								$tire_brand_farsi_name = $brands_array[ $b ]['farsi_name'];
								echo ">" . $tire_brand_farsi_name . "</option>";
							}

							?>

                        </select>


                    </td>
                    <td><select name="tire_size_selected">
							<?php

							foreach ( $tire_array as $t ) {
								echo "<option value=\"$t\"";
								if ( $t == $size ) {
									echo " selected";
								}
								echo ">$t</option>";
							}
							?>
                        </select></td>
                    <td>
                        <input name="tire_quantity_selected" type="number" size="4" value="<?php echo $quantity; ?>">
                    </td>
                    <td>
                        <input type="submit" value="ارسال">
                    </td>
                </tr>
                </tbody>
            </table>
        </form>


		<?php
	}
}

function tire_limit_admin_page() {
//    if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name) {
	$u = wp_get_current_user();
	if ( ! current_user_can( "level_0" ) ) {
		return;
	} elseif ( ! current_user_can( "level_1" ) ) {
		global $wpdb;
		require( tiremanager_plugin_dir_path . 'formsconfig.php' );
		require( tiremanager_plugin_dir_path . 'sellers_brands.php' );
		$user_name  = $u->first_name;
		$user_login = $u->user_login;
		$table_name = $wpdb->prefix . $tire_table_quantities_without_prefix_name;
		/*
		 * SELECT `id`, `tire_brand`,`tire_size`,`tire_quantity` FROM `wp_tire_seller` WHERE   `id` in (
		SELECT max(`id`) from `wp_tire_seller` where `tire_seller`='bnd_tire_bahmannejad' GROUP by `tire_brand`,`tire_size`
			)*/

		$query          = "SELECT `id`, `tire_brand`,`tire_size`,`tire_quantity` 
                FROM `$table_name` 
                WHERE   `id` in 
                                (
                        SELECT max(`id`) from `$table_name` 
                        where `tire_seller`='$user_login' 
                        and   tire_is_active =1
                        GROUP by `tire_brand`,`tire_size` 
                            )                        
                             and `tire_quantity` > 0
";
		$tire_db_result = $wpdb->get_results( $query, ARRAY_N );
		$row_id         = 0;
		?>
        <link rel="stylesheet" type="text/css"
              href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"/>
        <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
        <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
        <table id="tiretable" class="display" style="width:100%">
            <thead>
            <tr>
                <th>ردیف</th>
                <th>برند</th>
                <th>سایز</th>
                <th>موجودی</th>
				<?php if ( $tire_ware_house_limit and $seller_allow_edit_warehouse_limit ) { ?>
                    <th>ویرایش</th>
				<?php } ?>

            </tr>
            </thead>
            <tbody>
			<?php
			foreach ( $tire_db_result as $tire_detail ) {
				?>
                <tr>
                    <td><?php echo ++ $row_id; ?></td>
                    <td><?php echo $brands_array[ $tire_detail[1] ]['farsi_name']; ?></td>
                    <td><?php echo $tire_detail[2]; ?></td>
                    <td><?php echo $tire_detail[3]; ?></td>
					<?php if ( $tire_ware_house_limit and $seller_allow_edit_warehouse_limit ) { ?>

                        <td><a href="<?php
							$query_args = array(
								'page'       => 'tireedit',
								'seller'     => $user_login,
								'brand'      => $tire_detail[1],
								'size'       => $tire_detail[2],
								'quantity'   => $tire_detail[3],
								'redirected' => 'true',
							);
							echo esc_url( add_query_arg( $query_args, admin_url() . 'admin.php' ) ); ?>"
                            >
                                به‌روزرسانی
                            </a>
                        </td>
					<?php } ?>
                </tr>
				<?php

			}
			?>
            </tbody>
            <tfoot>
            <tr>
                <th>ردیف</th>
                <th>برند</th>
                <th>سایز</th>
                <th>تعداد</th>
                <th>به‌روزرسانی</th>

            </tr>
            </tfoot>
        </table>
        <script>
            $(document).ready(function () {
                    $('#tiretable').DataTable({
                            "pageLength": 100,
                            "language": {
                                "search": "جست و جو",
                                "Show": "نمایش",
                                "paginate": {
                                    "first": "اول",
                                    "last": "آخر",
                                    "next": "بعدی",
                                    "previous": "قبلی"
                                },
                                "info": "صفحه _PAGE_ از _PAGES_",
                                "lengthMenu": "نمایش _MENU_ مورد",

                            },

                        }
                    )
                }
            );
        </script>
		<?php
	} elseif ( current_user_can( 'level_1' ) ) {
		global $wpdb;
		require( tiremanager_plugin_dir_path . 'formsconfig.php' );
		require( tiremanager_plugin_dir_path . 'sellers_brands.php' );
		$table_name = $wpdb->prefix . $tire_table_quantities_without_prefix_name;
		$data_array = array();
		$row_id     = 0;
		foreach ( $sellers_array as $item => $value ) {
			$user_login     = $item;
			$query          = "SELECT `id`, `tire_brand`,`tire_size`,`tire_quantity` ,`tire_seller`
                FROM `$table_name` 
                WHERE   `id` in 
                                (
                        SELECT max(`id`) from `$table_name` 
                        where `tire_seller`='$user_login' 
                                                and   tire_is_active =1
                        GROUP by `tire_brand`,`tire_size` 
                            )";
			$tire_db_result = $wpdb->get_results( $query, ARRAY_N );
			$data_array     = array_merge( $data_array, $tire_db_result );

		}

		?>
        <link rel="stylesheet" type="text/css"
              href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"/>
        <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>

        <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
        <table id="tiretable" class="display" style="width:100%">
            <thead>
            <tr>
                <th>ردیف</th>
                <th>عامل</th>
                <th>برند</th>
                <th>سایز</th>
                <th>موجودی</th>
                <th>ویرایش</th>

            </tr>
            </thead>
            <tbody>

			<?php
			foreach ( $data_array as $tire_detail ) {
				?>
                <tr>
                    <td><?php echo ++ $row_id; ?></td>
                    <td><?php echo $sellers_array[ $tire_detail[4] ]['farsi_name'] ?></td>
                    <td><?php echo $brands_array[ $tire_detail[1] ]['farsi_name']; ?></td>
                    <td><?php echo $tire_detail[2]; ?></td>
                    <td><?php echo $tire_detail[3]; ?></td>
                    <td><a href="<?php
						$query_args = array(
							'page'       => 'tireedit',
							'seller'     => $tire_detail[4],
							'brand'      => $tire_detail[1],
							'size'       => $tire_detail[2],
							'quantity'   => $tire_detail[3],
							'redirected' => 'true',
						);

						echo esc_url( add_query_arg( $query_args, admin_url() . 'admin.php' ) ) ?>"
                        >
                            به‌روزرسانی
                        </a>
                    </td>
                </tr>

				<?php

			}
			?>
            </tbody>
            <tfoot>
            <tr>
                <th>ردیف</th>
                <th>عامل</th>
                <th>برند</th>
                <th>سایز</th>
                <th>تعداد</th>
                <th>به‌روزرسانی</th>

            </tr>
            </tfoot>
        </table>
        <script>
            $(document).ready(function () {
                    $('#tiretable').DataTable({
                            "pageLength": 100,
                            "language": {
                                "search": "جست و جو",
                                "Show": "نمایش",
                                "paginate": {
                                    "first": "اول",
                                    "last": "آخر",
                                    "next": "بعدی",
                                    "previous": "قبلی"
                                },
                                "info": "صفحه _PAGE_ از _PAGES_",
                                "lengthMenu": "نمایش _MENU_ مورد",

                            },

                        }
                    )
                }
            );
        </script>
		<?php
	}

//}
}

function my_login_redirect( $redirect_to, $request, $user ) {
	require( tiremanager_plugin_dir_path . 'sellers_brands.php' );
	if ( isset( $user->roles ) and is_array( $user->roles ) ) {
		if ( ! $user->has_cap( 'level_1' ) ) {
			$redirect_to = admin_url() . "admin.php?page=gf_inbox_new";
		} elseif ( ! $user->has_cap( 'level_9' ) ) {
			$redirect_to = admin_url() . "admin.php?page=tireadmin";
		}

	}

	return $redirect_to;
}

add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );


include_once get_home_path() . '/wp-content/plugins/tiremanager/formsconfig.php';

function shapeSpace_remove_toolbar_node( $wp_admin_bar ) { //remove someting from toolbar

	// replace 'updraft_admin_node' with your node id
	if ( ! current_user_can( 'level_5' ) ) {
		$wp_admin_bar->remove_node( 'wp-logo' );
		$wp_admin_bar->remove_node( 'comments' );
		$wp_admin_bar->remove_node( 'new-content' );
	}

}

add_action( 'admin_bar_menu', 'shapeSpace_remove_toolbar_node', 999 );
function my_login_logo_one() {
	?>
    <style type="text/css">
        body.login div#login h1 a {
            background-image: url(http://asnafhormozgan.com/wp-content/uploads/2017/03/cropped-logo-2-32x32.jpg);
        / / Add your own logo image in this url padding-bottom: 30 px;
        }
    </style>
	<?php
}

add_action( 'login_enqueue_scripts', 'my_login_logo_one' );

function my_login_logo_url() {
	return home_url();
}

add_filter( 'login_headerurl', 'my_login_logo_url' );


function my_login_logo_url_title() {
	return "سلام";
}

add_filter( 'login_headertitle', 'my_login_logo_url_title' );

add_filter( 'admin_footer_text', '__return_empty_string', 11 );
add_filter( 'update_footer', '__return_empty_string', 11 );

//validator for checking if exists in warehoused
register_activation_hook( __FILE__, 'installation_db' );
add_action( 'admin_menu', 'tire_limit_admin_menu', 999 ); //add admin page

add_action( 'admin_head', 'my_custom_fonts' );

function my_custom_fonts() {
	if ( ! current_user_can( 'level_9' ) ) {
		echo '<style>
    #gf_form_toolbar,.gf_admin_page_title {display: none;}
  </style>';
	}
}


function how_much_customer_for_date(

	$tire_delivery_day,
	$tire_seller,
	$is_j_date = true
) {
	require( tiremanager_plugin_dir_path . 'formsconfig.php' );
	require( tiremanager_plugin_dir_path . 'sellers_brands.php' );
	if ( ! $is_j_date ) {
		$tire_delivery_day = jdate( 'Y-m-d',
			$tire_delivery_day->toTimestamp(),
			false, false,
			'en' );
	}
	$entry_count = 0;
	foreach ( $tire_delivery_date_field_id as $day => $value ) {
		foreach ( $tire_gf_fields_id_sellers_array as $sf => $value ) {
			$search_criteria                    = array();
			$search_criteria['field_filters'][] = array( 'key' => "$day", 'value' => "$tire_delivery_day" );
			$search_criteria['field_filters'][] = array( 'key' => "$sf", 'value' => "$tire_seller" );
			$entry                              = GFAPI::count_entries( $tire_gravity_form_id, $search_criteria );
			$entry_count                        = $entry_count + $entry;
		}
	}

	return $entry_count;
}

/**
 * @return DateTime
 */
function reserveation_day( $seller = null ) {
	require( tiremanager_plugin_dir_path . 'formsconfig.php' );

	if ( ! function_exists( 'jdate' ) ) {
		date_default_timezone_set( 'Asia/Tehran' );
		include( tiremanager_plugin_dir_path . 'lib/jdf.php' );
	}

	if ( $seller == null ) {
		$seller = "bnd_tire_bahmannejad_behnam";
	}
	$tomorrow = new DateTime();
	$is_it    = 6;
	/** @var int $tire_seller_days_limitation is in formconfigs.php */
	$preregisterd = $tire_seller_days_limitation + 10;
	while ( $preregisterd >= $tire_seller_days_limitation or $is_it > 5 ) {
		$tomorrow->modify( '+1 day' );
		$timestamp = $tomorrow->getTimestamp();

		$jday         = jdate( 'Y-m-d', $timestamp,
			false,
			false,
			'en' );
		$today_epoch  = jalaliepoch( $jday );
		$is_it        = is_tatil( $jday );
		$preregisterd = how_much_customer_for_date( $jday, $seller );
	}

	return $tomorrow;
}


function delivery_date( $form ) {
	include tiremanager_plugin_dir_path . 'formsconfig.php';
	/** @var bool $auto_date_set */
	if ( ! $auto_date_set ) {
		return $form;
	}


	if ( ! defined( 'sellers_array' ) ) {
		include tiremanager_plugin_dir_path . 'sellers_brands.php';
	}
	if ( ! function_exists( 'jdate' ) ) {
		date_default_timezone_set( 'Asia/Tehran' );
		include( tiremanager_plugin_dir_path . 'lib/jdf.php' );
	}

	/** @var array $sellers_array */
	foreach ( $sellers_array as $seller => $value ) {
		$date      = reserveation_day( $seller );
		$timestamp = $date->getTimestamp();
		/** @var JsonSerializable $deliver_dates */
		$deliver_dates->$seller = jdate( 'Y-m-d', $timestamp,
			false,
			false,
			'en' );
	}
	/** @var TYPE_NAME $tire_gravity_form_id */
	/** @var TYPE_NAME $tire_delivery_date_field_id */
	/** @var TYPE_NAME $tire_gf_fields_id_sellers_array */
	echo '<script> 
 jQuery(document).ready(function(){
console.log("let begin");
const tarikhaa=;' . json_encode( $deliver_dates ) . ';
      const form_id=;' . $tire_gravity_form_id . ';
    const date_field_id=;' . json_encode( $tire_delivery_date_field_id ) . ';
    const sellers_id=;' . json_encode( $tire_gf_fields_id_sellers_array ) . ';

const date_field = Object.keys(date_field_id)[0];
const seller_list=Object.keys(sellers_id);
date_field_jq = jQuery("#input_"+form_id.toString()+"_"+date_field.toString());
//date_field_jq.prop("disabled",true );

function setDateField(e) {
 //   date_field_jq.prop("disabled",false );
    date_field_jq.val(tarikhaa[e.target.value]).change().click().keyup().keydown().keypress();
//        date_field_jq.prop("disabled",true );


}
for(let s=0;s<seller_list.length;s++){
    let input_id = "#input_"+form_id.toString()+"_"+seller_list[s].toString();
    console.log(input_id);
    jQuery(input_id).change(setDateField);
}
});

</script>';


	return $form;
}

add_filter( 'gform_pre_render_' . $tire_gravity_form_id, 'delivery_date' );


add_action( 'admin_head', 'hide_field_from_edit' );
if ( ! function_exists( 'getFieldById' ) ) {
	require_once( tiremanager_plugin_dir_path . 'edit_entry.php' );
}
if ( ! function_exists( 'listavailabletires' ) ) {
	include_once( tiremanager_plugin_dir_path . 'listavailabletires.php' );
}
require_once 'AutoFillFields.php';
